package com.mrd.serverconnect.widget;

/**
 * Created by cww on 2020/8/5.
 */
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

/**
 * Created by ZuoHailong on 2017/11/14.
 */

public class GradientColorTextView extends TextView {

    private LinearGradient mLinearGradient;
    private Paint mPaint;
    private int mViewWidth = 0;
    private Rect mTextBound = new Rect();
    private int measuredHeight=0;

    public GradientColorTextView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mViewWidth = getMeasuredWidth();
        measuredHeight = getMeasuredHeight();
        mPaint = getPaint();
        String mTipText = getText().toString();
        mPaint.getTextBounds(mTipText, 0, mTipText.length(), mTextBound);
        mLinearGradient = new LinearGradient(0, 0, 0, measuredHeight,
                new int[]{0xFFFFFFFF,0xFF00C0FF},
                null, Shader.TileMode.REPEAT);
        mPaint.setShader(mLinearGradient);
        int myGravity = getGravity();//渲染之前判断自己的对齐属性；


        int x = 0; //默认从左边开始画

        // 判断是不是从右边开始画
        if((myGravity&Gravity.RIGHT)==Gravity.RIGHT||(myGravity&Gravity.END)==Gravity.END){
            x = getMeasuredWidth()-mTextBound.width();
        }else if((myGravity&Gravity.CENTER)==Gravity.CENTER||(myGravity&Gravity.CENTER_HORIZONTAL)==Gravity.CENTER_HORIZONTAL){
            x = getMeasuredWidth()/2-mTextBound.width()/2;
        }
        canvas.drawText(mTipText, x , getMeasuredHeight() / 2 + mTextBound.height() / 2, mPaint);
    }
}
